package com.rz.htk.print.util;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import com.rz.htk.order.entity.Order;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;

public class PDFUtil {
    private static final String HTML = "print_temp.ftl";

    private static Configuration freemarkerCfg;

    static {
        freemarkerCfg = new Configuration(Configuration.VERSION_2_3_28);
        freemarkerCfg.setClassForTemplateLoading(PDFUtil.class,"/templates");
    }

    /**
     * freemarker渲染html
     */
    public static String freeMarkerRender(Order order) {
        Writer out = new StringWriter();
        try {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(HTML);
            // 合并数据模型与模板
            template.process(order, out); //将合并后的数据和模板写入到流中，这里使用的字符流
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    private static final String FONT = "fangsong.ttf";
    public static ITextRenderer createPdf(OutputStream output,Order model,Boolean finish) throws IOException, DocumentException {
        ITextRenderer render = new ITextRenderer();
        ITextFontResolver fontResolver = render.getFontResolver();
        ClassPathResource classPathResource = new ClassPathResource(FONT);
        fontResolver.addFont(classPathResource.getPath(),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        String firstContent = PDFUtil.freeMarkerRender(model);
        render.setDocumentFromString(firstContent);
        render.layout();
        render.createPDF(output,finish);
        return render;
    }

}
